package com.zlf.mvc.config;

import com.zlf.entity.Admin;
import com.zlf.entity.Role;
import com.zlf.service.api.AdminService;
import com.zlf.service.api.AuthService;
import com.zlf.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：张利锋
 * @date ：Created in 2020/11/22 19:52
 * @description： TOOD
 * @version: 1.0
 */
@Component
public class CrowdUserDetailService implements UserDetailsService {
    @Autowired
    AdminService adminService;
    @Autowired
    AuthService authService;
    @Autowired
    RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据用户名从数据库查询 Admin 对象
        List<Admin> adminList = adminService.getAdminByLoginAcct(username);
        if (adminList==null || adminList.size()!=1){
            return null;
        }
        Admin admin=adminList.get(0);
        // 2.获取数据库中密码
        String userpswd=admin.getUserPswd();
        // 3.查询 Admin 对应的权限信息（包括角色、权限）
        Integer adminId=admin.getId();
        // ①创建集合用来存放权限信息
        List<GrantedAuthority> authorities=new ArrayList<>();
        // ②根据 adminId 查询对应的角色
        List<Role> roleList = roleService.getAssignedRole(adminId);
        for (Role role:roleList){
            String roleName = role.getName();
            // 注意：一定要加“ROLE_”
            authorities.add(new SimpleGrantedAuthority("ROLE_"+roleName));
        }
        // ③根据 adminId 查询对应的权限
        List<String> authNameList = authService.getAuthNameByAdminId(adminId);
        for (String authName:authNameList){
            authorities.add(new SimpleGrantedAuthority(authName));
        }
        // 4.封装到 User 的子类 SecurityAdmin 类型的对象中
        SecurityAdmin securityAdmin=new SecurityAdmin(admin,authorities);

        return securityAdmin;
    }
}
